#include "checkboxdelegate.h"
#include <QCheckBox>
#include <QApplication>
#include <QMouseEvent>
#include <QDebug>

CheckBoxDelegate::CheckBoxDelegate(QObject *parent)
    :QStyledItemDelegate(parent)
{

}

//用来设置表格样式，绘制复选框-状态、大小、显示区域等。
void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem viewOption(option);
    //The QStyleOptionViewItem class is used to describe the parameters used to draw an item in a view widget

    initStyleOption(&viewOption,index);//When reimplementing paint in a subclass. Use the initStyleOption() to set up the option in the same way as the QStyledItemDelegate.

//    qDebug() << index.column();

    if (option.state.testFlag(QStyle::State_HasFocus))
        viewOption.state = viewOption.state ^ QStyle::State_HasFocus;
    QStyledItemDelegate::paint(painter,viewOption,index);

    if (index.column() == CHECK_BOX_COLUMN) {
        bool data = index.model()->data(index,Qt::UserRole).toBool();

        QStyleOptionButton checkBoxStyle;
        checkBoxStyle.state = data ? QStyle::State_On : QStyle::State_Off;
        checkBoxStyle.state |= QStyle::State_Enabled;
        checkBoxStyle.iconSize = QSize(20,20);
        checkBoxStyle.rect = option.rect;
//        checkBoxStyle.rect.setSize(QSize(20,20));

        QCheckBox checkBox;
        QApplication::style()->drawPrimitive(QStyle::PE_IndicatorCheckBox,
                                             &checkBoxStyle,painter,&checkBox);
    }
}

//用来设置数据，响应鼠标事件，判断当前选中状态，互相切换。
bool CheckBoxDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    QRect decorationRect = option.rect;
    QMouseEvent * mouseEvent = static_cast<QMouseEvent * >(event);
    if (event->type() == QEvent::MouseButtonPress &&
            decorationRect.contains(mouseEvent->pos())) {//如果是鼠标压下事件且事件发生的点存在于当前项窗体所在的区域内，则被认为复选框被点击
        if (index.column() == CHECK_BOX_COLUMN) {
            bool data = model->data(index,Qt::UserRole).toBool();
            model->setData(index,!data,Qt::UserRole);
        }
    }

    return QStyledItemDelegate::editorEvent(event,model,option,index);
}
